package com.compass.mobile.ui.activity

import LogUtil
import UserInfoManager
import android.content.Context
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.text.Editable
import android.view.View
import android.view.View.VISIBLE
import android.widget.RadioButton
import androidx.activity.viewModels
import androidx.annotation.RequiresApi
import androidx.core.widget.addTextChangedListener
import androidx.lifecycle.lifecycleScope
import com.compass.mobile.R
import com.compass.mobile.callback.OnCustomButtonClick
import com.compass.mobile.databinding.ActivityAddPatientBinding
import com.compass.mobile.framework.base.BaseVBActivity
import com.compass.mobile.framework.constant.ADD_PATIENT
import com.compass.mobile.framework.constant.COMMOM_VERIF_CODE
import com.compass.mobile.framework.constant.KEY_PHONE
import com.compass.mobile.framework.constant.REFRESH_PATIENT
import com.compass.mobile.framework.constant.YD_USER_ID
import com.compass.mobile.framework.ext.gone
import com.compass.mobile.framework.ext.onClick
import com.compass.mobile.framework.ext.visible
import com.compass.mobile.framework.utils.FocusViewUtils
import com.compass.mobile.framework.utils.LiveDataBus
import com.compass.mobile.framework.utils.PatientDataUtil
import com.compass.mobile.framework.utils.QRCodeDealUtils
import com.compass.mobile.ui.dialog.InputPhoneDialog
import com.compass.mobile.ui.viewModel.UserViewModel
import dp2px
import countDownCoroutines
import getStringFromResource
/**
 * Description： 绑定就诊人
 * Date:2024/6/20 10:30
 */
class AddPatientActivity : BaseVBActivity<ActivityAddPatientBinding>() {
    private val userViewModel: UserViewModel by viewModels()

    companion object {
        fun start(context: Context,phone:String) {
            val intent = Intent(context, AddPatientActivity::class.java)
            intent.putExtra(KEY_PHONE,phone)
            context.startActivity(intent)
        }
    }

    override fun initView(savedInstanceState: Bundle?) {
//        FocusViewUtils.scaleView(mBinding.tvGetCode, 1)
//        FocusViewUtils.scaleView(mBinding.tvSave, 1)
        mBinding.radioSexMail.isChecked = true
        mBinding.topView.setPatientViewVisible(false)

    }

    private var isClick = true
    private var phoneNumber: String? = null
    private var code: String? = null
    private var mBindType: String = "1"
    private var mOldMobile:String? = null
    private var mOldCode:String? = null
    private var mSelectedValue:String? = "男"
    override fun intListener() {
        mBinding.tvGetCode.onClick {
           val phone = mBinding.etPhone.text.toString().trim()

            if(phone.isEmpty()){
                showToast("请输入手机号")
                return@onClick
            }
            if (isClick) {
                phoneNumber = mBinding.etPhone.text.toString().trim()
                userViewModel.getCode(phoneNumber)
                countDownCoroutines()
            }
        }

        mBinding.radioSex.setOnCheckedChangeListener { group, checkedId ->
            val radioButton = findViewById<RadioButton>(checkedId)
            mSelectedValue = radioButton.text.toString()
            // 使用selectedValue进行你需要的操作
        }

        mBinding.etCardno.addTextChangedListener{
            it?.let {
                if(it.isNotEmpty()){
                    val cardNo = it.toString().trim()
                    //检测正确的身份证，并从输入的身份证号码从提取年龄数据，回填在年龄输入框，如果身份证年龄小于14岁则显示出监护人信息
                    if(PatientDataUtil.checkValidIdNumber(cardNo)){
                        val age:Int =  PatientDataUtil.getAgeByIdNumber(cardNo)
                        if(age>0){
                            mBinding.etAge.setText(age.toString())
                        }
                        if(age < PatientDataUtil.UNDERAGE){
                            mBinding.llGuardian.visible()
                        }else{
                            mBinding.llGuardian.gone()
                        }
                    }else{
                        mBinding.apply {
                            llGuardian.gone()
                            etAge.setText("")
//                            etGuardianCardno.setText("")
//                            etGuardianPhone.setText("")
//                            etGuardianName.setText("")
                        }
                    }
                }else{
                    mBinding.apply {
                        llGuardian.gone()
                        etGuardianCardno.setText("")
                        etGuardianPhone.setText("")
                        etGuardianName.setText("")
                        etAge.setText("")
                    }

                }
            }
        }
        mBinding.tvSave.onClick {
            phoneNumber = mBinding.etPhone.text.toString().trim()
            code = mBinding.etCode.text.toString().trim()
            val name = mBinding.etName.text.toString().trim()
            val cardNo = mBinding.etCardno.text.toString().trim()
            val age = mBinding.etAge.text.toString().trim()
            var sex = 0

            when(mSelectedValue){
                "男"->sex = 1
                "女"->sex = 2
                "未知"->sex = 0
            }

            //监护人信息
            val guardianName= mBinding.etGuardianName.text.toString().trim()
            val guardianCardNo = mBinding.etGuardianCardno.text.toString().trim()
            val guardianPhone = mBinding.etGuardianPhone.text.toString().trim()

            //保存
            if(phoneNumber.isNullOrEmpty()){
                showToast("请输入手机号")
                return@onClick
            }

            if(isCheckCode){
                if(code.isNullOrEmpty()){
                    showToast("请输入验证码")
                    return@onClick
                }
            }else{
                code = COMMOM_VERIF_CODE
            }

            if(name.isEmpty()){
                showToast("请输入姓名")
                return@onClick
            }
            if(cardNo.isEmpty() || !PatientDataUtil.checkValidIdNumber(cardNo)){
                showToast("请输入正确的身份证号码")
                return@onClick
            }
            if(age.isEmpty()){
                showToast("请输入年龄")
                return@onClick
            }
//            if(sex.isEmpty()){
//                showToast("请输入性别")
//                return@onClick
//            }
            if(PatientDataUtil.isUnderage(cardNo)){
                //未成年的情况，需要验证监护人信息
                if(!PatientDataUtil.checkValidIdNumber(guardianCardNo)){
                    showToast("请输入正确的监护人身份证号")
                    return@onClick
                }

                if(guardianName.isEmpty()){
                    showToast("请输入正确的监护人姓名")
                    return@onClick
                }

                if(guardianPhone.isEmpty()){
                    showToast("请输入正确的监护人手机号")
                    return@onClick
                }
            }
            if(mBindType == "3"){
                if(mOldMobile.isNullOrEmpty() || mOldMobile?.length != 11){
                    showToast("请输入原手机号")
                    return@onClick
                }

                if(mOldMobile.isNullOrEmpty() || mOldMobile?.length != 4){
                    showToast("请输入原手机号验证码")
                    return@onClick
                }
            }
            userViewModel.addPatients(name,cardNo, phoneNumber!!, code!!,sex,age,mBindType,guardianName,guardianCardNo,guardianPhone,mOldMobile,mOldCode)
        }
    }
    //是否检测验证码
    private var isCheckCode = false
    override fun initData() {
        val qrCodeUrl = ADD_PATIENT + UserInfoManager.getString(YD_USER_ID)
        LogUtil.d("qrCodeUrl===$qrCodeUrl")
        val phone:String? = intent.getStringExtra(KEY_PHONE)
        phone?.let {
            mBinding.etPhone.setText(phone)
//            mBinding.etPhone.setEditableFactory(Editable.)
            mBinding.llVerifCode.gone()
            isCheckCode = false
            mBinding.etPhone.isEnabled = false
        }?:kotlin.run(){
            mBinding.llVerifCode.visible()
            mBinding.etPhone.isEnabled = true
            isCheckCode = true
        }
        mBinding.ivQrcode.setImageBitmap(
            QRCodeDealUtils.generateQRCodeWithoutMargin(
                qrCodeUrl,
                dp2px(400f),
                dp2px(400f)
            )
        )
        userViewModel.addPatientLiveData.observe(this){
            if(it){
                LiveDataBus.get().with(REFRESH_PATIENT).postValue(REFRESH_PATIENT)
                //添加成功
                this.finish()
            }
        }

        userViewModel.modifyPatientLiveData.observe(this){
            if(it){
                //修改用户数据
                mBindType = "3"
                val inputPhoneDialog = InputPhoneDialog.Builder(this@AddPatientActivity, onPhoneClick)
                inputPhoneDialog.show()
            }
        }

    }

    private var onPhoneClick : OnCustomButtonClick =  object : OnCustomButtonClick {
        override fun onButtonCallBack(codeType: Int, msgType: String?) {
            super.onButtonCallBack(codeType, msgType)
            when(codeType){
                1->{
                    //发送验证码
                    mOldMobile = msgType
                }
                2->{
                    mOldCode = msgType
                }
            }
        }
    }
    /**
     * 倒计时
     */
    private fun countDownCoroutines() {
        //倒计时
        countDownCoroutines(59, lifecycleScope, onTick = {
            isClick = false
            mBinding.tvGetCode.text =
                getStringFromResource(R.string.sms_tip, it.plus(1).toString())
        }) {
            isClick = true
            mBinding.tvGetCode.text = "获取验证码"
        }
    }


}